package com.gtw.modules.sys.controller;

import com.gtw.common.annotation.SysLog;
import com.gtw.common.utils.PageUtils;
import com.gtw.common.utils.Query;
import com.gtw.common.utils.R;
import com.gtw.distribution.DistributionUtil;
import com.gtw.distribution.IntegralClearingUtil;
import com.gtw.modules.api.service.TbCommodityPropertyService;
import com.gtw.modules.api.service.TbEnergyvalueNotesService;
import com.gtw.modules.api.service.TbUserService;
import com.gtw.modules.dao.TbCapitalpoolDao;
import com.gtw.modules.entity.*;
import com.gtw.modules.sys.service.SysDividendRuleservice;
import com.gtw.modules.sys.service.TbProxyFavorableService;
import com.gtw.modules.sys.service.TbReplenishService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wuye on 2018/3/26.
 */
@RestController
@RequestMapping("/sys/replenish")
public class SysTbReplenishController {

    @Autowired
    private TbReplenishService replenishService;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbProxyFavorableService tbProxyFavorableService;

    @Autowired
    private DistributionUtil distributionUtil;

    @Autowired
    private TbEnergyvalueNotesService tbEnergyvalueNotesService;

    @Autowired
    private SysDividendRuleservice sysDividendRuleservice;

    @Autowired
    private TbCapitalpoolDao tbCapitalpoolDao;

    @Autowired
    private IntegralClearingUtil integralClearingUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:replenish:list")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);

        List<TbReplenish> replenishList = replenishService.queryList(query);
        int total = replenishService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(replenishList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:replenish:info")
    public R info(@PathVariable("id") Integer id){
        TbReplenish replenish = replenishService.queryObject(id);
        replenish.setMoney(replenish.getMoney()/100);
        return R.ok().put("replenish", replenish);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:replenish:save")
    public R save(@RequestBody TbReplenish replenish){
        replenishService.save(replenish);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:replenish:update")
    public R update(@RequestBody TbReplenish replenish){
        replenish.setUpdaetdate(new Date());
        replenishService.update(replenish);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:replenish:delete")
    public R delete(@RequestBody Integer[] ids){
        replenishService.deleteBatch(ids);

        return R.ok();
    }


    /**
     * 批准进货
     * @return
     */
    @SysLog("代理进货批准")
    @RequestMapping("/Approved")
    public R Approved(@RequestBody Integer id){
        System.out.println("进入发货:"+id);
        TbReplenish tbReplenish = replenishService.queryObject(id);
        System.out.println("查询到进货单   金额:"+tbReplenish.getMoney());
        if(tbReplenish.getState() ==2){
            return R.error().put("msg","已经审核过了");
        }
        if(tbReplenish.getState() == 3){
            return R.error().put("msg","已经审核过了");
        }
        TbUser tbUserr = tbUserService.queryById(tbReplenish.getUserid());
        tbReplenish.setState(2);
        tbReplenish.setUpdaetdate(new Date());
        replenishService.update(tbReplenish);
        //修改用户身份及对应库存
        //根据订单金额判断属于哪个级别
        List<TbProxyFavorable> proxyFavorableList = tbProxyFavorableService.queryAll();
        for (TbProxyFavorable pf: proxyFavorableList) {
            if((tbReplenish.getMoney())>=pf.getMinprice()&&(tbReplenish.getMoney())<=pf.getMaxprice()){
                tbUserr.setAgentlevel(1);
                //计算原价
                int qian = (int) (tbReplenish.getMoney()/(pf.getProportion()));
                System.out.println("计算原价:"+qian);
                //累计库存
                tbUserr.setAgentinventory(tbUserr.getAgentinventory()+qian);
                System.out.println("用户库存:"+tbUserr.getAgentinventory());
                tbUserr.setType(2);
                tbUserService.update(tbUserr);
                //累计能量值积分
//                tbUser.setEnergyvalue(tbUser.getEnergyvalue()+(tbReplenish.getMoney()/100));
//                tbUserService.update(tbUser);
//                //对应积分
                //订单金额
//                Float money = tbOrder.getTotalfee()/100;
//                //对应积分
//                Integer jifen = (int) (money + 0);
                Integer jifen = (tbReplenish.getMoney()/100);
                System.out.println("本次获取的能量值:"+jifen);
                TbUser tbUser = tbUserService.queryById(tbReplenish.getUserid());
                //上级累积
                if(tbUser != null) {
                    tbUser.setEnergyvalue(tbUser.getEnergyvalue() + jifen);
                    System.out.println("用户的积分:"+tbUser.getEnergyvalue());
                    int result = tbUserService.update(tbUser);
                    System.out.println("修改用户积分是否执行成功:"+result);
                    //积分等级换算
                    integralClearingUtil.distribution5(tbUser);
                    //积分收益明细
                    TbEnergyvalueNotes tbEnergyvalueNotes0 = new TbEnergyvalueNotes();
                    tbEnergyvalueNotes0.setCreattime(new Date());
                    tbEnergyvalueNotes0.setValue(jifen);
                    tbEnergyvalueNotes0.setType(0);
                    tbEnergyvalueNotes0.setOrderid(0);
                    tbEnergyvalueNotes0.setUid(tbUser.getUuid());
                    tbEnergyvalueNotes0.setOrderid(0);
                    tbEnergyvalueNotesService.save(tbEnergyvalueNotes0);

                    if(tbUser .getParentid() != null) {
                        //第一级受益人
                        TbUser tbUser1 = tbUserService.queryById(tbUser.getParentid());
                        if (tbUser1 != null) {
                            System.out.println("第一级受益人:" + tbUser1.getUsername());
                            //计算第一级受益人享受金额
                            tbUser1.setEnergyvalue(tbUser1.getEnergyvalue() + jifen);
                            System.out.println("第一级受益人积分:" + tbUser1.getEnergyvalue());
                            int result1 = tbUserService.update(tbUser1);
                            System.out.println("第一级受益人积分是否修改成功:" + result1);
                            //积分等级换算
                            integralClearingUtil.distribution5(tbUser1);
                            //积分收益明细
                            TbEnergyvalueNotes tbEnergyvalueNotes1 = new TbEnergyvalueNotes();
                            tbEnergyvalueNotes1.setCreattime(new Date());
                            tbEnergyvalueNotes1.setValue(jifen);
                            tbEnergyvalueNotes1.setType(0);
                            tbEnergyvalueNotes1.setUid(tbUser1.getUuid());
                            tbEnergyvalueNotes1.setOrderid(0);
                            tbEnergyvalueNotesService.save(tbEnergyvalueNotes1);
                            //第二级受益人
                            if (tbUser1.getParentid() != null) {
                                TbUser tbUser2 = tbUserService.queryById(tbUser1.getParentid());
                                if (tbUser2 != null) {
                                    System.out.println("第二级受益人:" + tbUser2.getUsername());
                                    tbUser2.setEnergyvalue(tbUser2.getEnergyvalue() + jifen);
                                    System.out.println("第二级受益人积分:" + tbUser2.getEnergyvalue());
                                    int result2 = tbUserService.update(tbUser2);
                                    System.out.println("第二级受益人积分是否修改成功:" + result2);
                                    //积分等级换算
                                    integralClearingUtil.distribution5(tbUser2);
                                    //积分收益明细
                                    TbEnergyvalueNotes tbEnergyvalueNotes2 = new TbEnergyvalueNotes();
                                    tbEnergyvalueNotes2.setCreattime(new Date());
                                    tbEnergyvalueNotes2.setValue(jifen);
                                    tbEnergyvalueNotes2.setType(0);
                                    tbEnergyvalueNotes2.setOrderid(0);
                                    tbEnergyvalueNotes2.setUid(tbUser2.getUuid());
                                    tbEnergyvalueNotes2.setOrderid(0);
                                    tbEnergyvalueNotesService.save(tbEnergyvalueNotes2);
                                }
                            }
                        }
                    }
                }
                TbDividendRule tbDividendRule2 = sysDividendRuleservice.queryObject(2);//代理
                //资金池叠加
                float dis = tbReplenish.getMoney() * tbDividendRule2.getProportion();
                System.out.println("代理资金池此次金额："+dis);
                TbCapitalpool tbCapitalpool = new TbCapitalpool();
                tbCapitalpool = tbCapitalpoolDao.selectByPrimaryKey(2);
                tbCapitalpool.setAmount(tbCapitalpool.getAmount() + dis);
                int result = tbCapitalpoolDao.updateByPrimaryKey(tbCapitalpool);
                System.out.println("资金池叠加执行："+result);
//                TbUser tbUser1 = tbUserService.queryById(tbUser.getParentid());
//                if(tbUser1 != null){
//                    tbUser1.setEnergyvalue(tbUser1.getEnergyvalue()+(tbReplenish.getMoney()/100));
//                    tbUserService.update(tbUser1);
//                    TbUser tbUser2 = tbUserService.queryById(tbUser1.getParentid());
//                    if(tbUser2 != null){
//                        tbUser2.setEnergyvalue(tbUser2.getEnergyvalue()+(tbReplenish.getMoney()/100));
//                        tbUserService.update(tbUser2);
//                    }
//                }
                //代理进货抽佣
                distributionUtil.distribution2(tbReplenish);
            }
        }
        return R.ok();
    }


    /**
     * 进货拒绝
     * @return
     */
    @SysLog("代理进货拒绝")
    @RequestMapping("/Refuse")
    public R Refuse(@RequestBody Integer id){
        TbReplenish tbReplenish = replenishService.queryObject(id);
        if(tbReplenish.getState() ==2){
            return R.error().put("msg","已经审核过了");
        }
        if(tbReplenish.getState() == 3){
            return R.error().put("msg","已经审核过了");
        }
        tbReplenish.setState(3);
        replenishService.update(tbReplenish);
        return R.ok();
    }
}
